package com.windrift.springhibernate.controller;

import com.windrift.common.bean.Option;
import com.windrift.springhibernate.model.IncomeType;
import com.windrift.springhibernate.service.IncomeTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xuweigui
 *
 */
@SuppressWarnings("serial")
@Controller
@RequestMapping(value="/incometype")
public class IncomeTypeController {


    @Autowired
    private IncomeTypeService incomeTypeService;

    @RequestMapping(value = "/remove/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public void deleteIncomeType(@PathVariable("id") Integer id ) {
          incomeTypeService.remove(id);
    }

    @RequestMapping()
    public String list(Model model) {
        List<IncomeType> incomeTypes = incomeTypeService.findAll();
        model.addAttribute("incomeTypes", incomeTypes);
        return "manage/IncomeTypeList";
    }
    //get income types
    @RequestMapping(value = "/option/{parentId}", method = RequestMethod.GET)
    @ResponseBody
    public List<Option> getIncomeTypeOption(@PathVariable("parentId") Integer parentId) {
        List<IncomeType> incomeTypes  = incomeTypeService.findChildren(parentId);
        return toOptions(incomeTypes);
    }
    @RequestMapping(value = "/option", method = RequestMethod.GET)
    @ResponseBody
    public List<Option> getIncomeTypeOption() {
        List<IncomeType> incomeTypes =  incomeTypeService.findAll();
        return toOptions(incomeTypes);
    }

    private List<Option> toOptions(List<IncomeType> incomeTypes) {
        List<Option> options = new ArrayList<Option>();
        for(IncomeType incomeType : incomeTypes) {
            Option option = new Option();
            option.setId(incomeType.getId());
            option.setName(incomeType.getName());
            option.setParentId(incomeType.getParentId());
            options.add(option);
        }
        return options;
    }

    @RequestMapping(value="/add", method = RequestMethod.POST)
    @ResponseBody
    public IncomeType createIncomeType(@RequestParam("parentId") Integer parentId, @RequestParam("name") String name) {
        IncomeType incomeType = new IncomeType();
        incomeType.setParentId(parentId);
        incomeType.setName(name);
        incomeTypeService.add(incomeType);
        return incomeType;
    }


    public void setIncomeTypeService(IncomeTypeService incomeTypeService) {
        this.incomeTypeService = incomeTypeService;
    }

}
